<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card shadow="never">
        <el-form :model="tagForm" ref="tagForm">
          <div class="filter-container">
            <el-row :gutter="24">
              <el-col :span="6">
                <el-form-item label="标签名称" prop="tagName">
                  <el-input
                    style="width: 180px;"
                    placeholder="请输入"
                    class="filter-item"
                    v-model="tagForm.tagName"
                    @keyup.enter="search"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item label="状态" prop="state">
                  <el-select
                    class="filter-item"
                    style="width: 180px;"
                    clearable
                    v-model="tagForm.state"
                  >
                    <el-option
                      v-for="item in status"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-button @click="clear">清除</el-button>
                <el-button type="primary" @click="search">搜索</el-button>
              </el-col>
              <el-col :span="8">
                <router-link class="returnSubject" to="/subjects/list" v-if="$route.query.id">
                <i class="el-icon-back"></i>返回学科</router-link>
                <el-button
                  class="filter-item fr"
                  size="small"
                  style="margin-left: 10px;"
                  type="success"
                  icon="el-icon-edit"
                  @click="openDialog('add',$event)"
                >新增标签</el-button>
              </el-col>
            </el-row>
          </div>
          <!-- 数据记录 -->
          <el-alert
            v-if="cResultTip"
            :title="cResultTip"
            type="info"
            class="alert"
            :closable="false"
            show-icon
          ></el-alert>
          <!-- end -->
          <!-- 数据列表 -->
          <el-table
            :data="companys"
            v-loading="isLoading"
            element-loading-text="给我一点时间"
            fit
            highlight-current-row
            style="width: 100%"
          >
            <el-table-column label="序号" width="70">
              <template slot-scope="{$index}">
                <span>{{ $index +1 }}</span>
              </template>
            </el-table-column>
            <el-table-column label="所属学科">
              <template slot-scope="scope">
                <span>{{scope.row.subjectName}}</span>
              </template>
            </el-table-column>
            <el-table-column label="标签名称">
              <template slot-scope="scope">
                <span>{{scope.row.tagName}}</span>
              </template>
            </el-table-column>
            <el-table-column label="创建者">
              <template slot-scope="scope">
                <span>{{scope.row.username}}</span>
              </template>
            </el-table-column>
            <el-table-column label="创建日期">
              <template slot-scope="scope">
                <span>{{scope.row.addDate}}</span>
              </template>
            </el-table-column>
            <el-table-column label="状态" width="80" prop="state" :formatter="formatState">
              <template slot-scope="scope">
                <span v-if="scope.row.state==1">已启用</span>
                <span v-else>已禁用</span>
              </template>
            </el-table-column>
            <!-- 操作按钮 -->
            <el-table-column
              label="操作"
              width="280"
              class-name="small-padding fixed-width"
            >
            <template slot-scope="{row}">
              <el-button
                type="text"
                @click="hSwitchStatus(row)"
                >
                  <span v-if="row.state === 0">启用</span>
                  <span v-else>禁用</span>
                </el-button>

              <el-button
                type="text"
                :disabled="row.state =='0'"
                @click="openDialog('edit',row)"
                >修改</el-button
              >
              <el-button
                type="text"
                :disabled="row.state == '0'"
                @click="hDelete(row)"
                >删除</el-button
              >
            </template>
            </el-table-column>
          </el-table>
          <!-- end -->
          <!-- 分页 -->
          <el-pagination
            background
            layout="prev, pager, next, sizes, jumper "
            style="text-align: right; margin-top: 24px;"
            :current-page="Number(tagForm.page)"
            :total="Number(total)"
            :page-size="Number(tagForm.pagesize)"
            :page-sizes="[10,20,30,50]"
            @current-change="hCurrentChange"
            @size-change="hSizeChange"
            >
          </el-pagination>
        </el-form>
        <!-- 新增弹层 -->
        <el-dialog
        style="font-size:22px"
        :visible.sync="isShowDialog"
        width="25%"
        @close="close"
        :tagId="curTagId"
        :title="title"
        >
        <el-form ref="addForm" label-width="100px" :model="addForm" :rules="addFormRules">
          <el-form-item label="所属学科" prop="subjectID" v-if="!$route.query.id">
            <el-select style="width:100%" v-model="addForm.subjectID" @change="handleSelectChange">
               <el-option
                v-for="item in subjectList"
                :key="item.id"
                :label="item.subjectName"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="目录名称" prop="tagName">
            <el-input placeholder="请输入目录名称" v-model="addForm.tagName"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button @click="close">取消</el-button>
            <el-button type="primary" @click="btnOk">确认</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
      </el-card>
    </div>
  </div>
</template>

<script>
import { status } from '@/api/hmmm/constants'
import { list as getTags, remove, changeState, add, update, detail } from '@/api/hmmm/tags'
import { list as getSubject } from '@/api/hmmm/subjects'
import { parseTime } from '@/utils/index'
export default {
  data () {
    return {
      companys: [],
      subjectList: [],
      total: 0,
      isLoading: false,
      isShowDialog: false,
      tagName: '',
      title: '',
      formLabelWidth: '80px',
      tagForm: {
        tags: '',
        state: '',
        page: 1,
        pagesize: 10,
        tagName: ''
      },
      addForm: {
        subjectID: null,
        tagName: '',
        id: ''
      },
      addFormRules: {
        tagName: [
          { required: true, message: '请输入目录名称', trigger: 'blur' }
        ],
        subjectID: [
          { required: true, message: '请输入所属学科', trigger: 'blur' }
        ]
      },
      curTagId: null // 区别于是否是编辑，还是添加
    }
  },
  // 创建完毕,做一次查询
  async created () {
    await this.loadCompanys()
    await this.getSubjectList()
    await this.getTimeList()
    // console.log(this.$route.query.id);
  },
  computed: {
    status () {
      return status
    },
    cResultTip () {
      return `共 ${this.total} 条记录`
    },
    cTitle () {
      return this.curTagId ? '编辑标签' : '添加标签'
    }
  },
  methods: {
    buildParams () {
      const paramsObj = {}
      const { page, pagesize, tagName, state } = this.tagForm
      // 如果某一个参数是null,则axios就不会发这个参数
      // 如果某一个参数是""，axios是会发出这个参数
      paramsObj.page = page || null
      paramsObj.pagesize = pagesize || null
      paramsObj.tagName = tagName || null
      paramsObj.state = state === '' ? null : state
      return paramsObj
    },
    // 获取列表数据
    async loadCompanys () {
      this.isLoading = true
      // 构建查询参数
      const paramsObj = this.buildParams()
      if (this.$route.query.id) {
        this.addForm.subjectID = this.$route.query.id
        const { data } = await getTags(this.addForm)
        this.companys = data.items
        this.total = data.counts
        // console.log(res);
        this.isLoading = false
      } else {
        try {
          const res = await getTags(paramsObj)
          // 获取数据给companys
          this.companys = res.data.items
          // 获取总条数
          this.total = res.data.counts
          this.isLoading = false
        } catch (err) {
          this.isLoading = true
        }
      }
    },
    getTimeList () {
      this.companys.forEach(item => {
        item.addDate = parseTime(item.addDate)
      })
    },
    // 点击某一个页码
    hCurrentChange (changePage) {
      this.tagForm.page = changePage
      this.loadCompanys()
    },
    hSizeChange (val) {
      this.tagForm.pagesize = val
      if (this.tagForm.page === 1) {
        this.loadCompanys()
      }
    },
    formatState (row, column, cellValue, index) {
      const obj = getTags.find(item => {
        return item.value === cellValue
      })
      return obj
    },
    async hSwitchStatus (row) {
      row.state = row.state ? 0 : 1
      this.companys.forEach(item => {
        if (item.id === row.id) {
          item.state = row.state
        }
      })
      await changeState(row)
    },
    // 渲染学科列表
    async getSubjectList () {
      const res = await getSubject()
      this.subjectList = res.data.items
    },
    handleSelectChange (value) {
      this.addForm.subjectID = value
    },
    // 打开弹框
    async openDialog (type, row) {
      this.type = type
      // console.log(type, row.id)
      if (type === 'add') {
        this.isShowDialog = true
        this.title = '添加标签'
      }
      if (type === 'edit') {
        this.title = '修改标签'
        this.isShowDialog = true
        const res = await detail(row)
        this.addForm.id = row.id
        if (this.addForm.id) {
          this.addForm = res.data
        }
      }
    },
    // 对话框确认按钮
    btnOk () {
      // 增加标签
      this.$refs.addForm.validate(async (valid) => {
        if (valid) {
          // 判断是否有id,有就是编辑，没有就是新增
          if (this.addForm.id) {
            await update(this.addForm)

            this.loadCompanys()
            this.close()
            this.$message.success('修改标签成功')
          } else {
            if (this.$route.query.id) {
              this.addForm.subjectID = Number(this.$route.query.id)
              await add(this.addForm)
              this.page = 1
              this.loadCompanys()
              this.close()
              this.$message.success('新增标签成功')
            } else {
              await add(this.addForm)
              this.page = 1
              this.loadCompanys()
              this.close()
              this.$message.success('新增标签成功')
            }
          }
        } else {
          return false
        }
      })
    },
    close () {
      this.$refs.addForm.resetFields()
      this.isShowDialog = false
    },
    // 删除
    async hDelete (row) {
      // console.log(id)
      this.$confirm('此操作将永久删除该学科, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        await remove(row)
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
        this.loadCompanys()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 搜索信息
    search () {
      if (!this.tagForm) return
      // 重置页码
      this.tagForm.page = 1
      // 重发请求
      this.loadCompanys()
    },
    // 清除信息
    clear () {
      this.tagForm.tagName = ''
      this.tagForm.state = null
      this.loadCompanys()
    }
  }
}
</script>

<style lang="scss" scoped>
.el-table th {
  background-color: #fafafa;
}
.el-table th.is-leaf {
  border-bottom: 2px solid #e8e8e8;
}
.disabled td {
  background-color: #f9f9f9;
  color: #c1c1c1;
}
.disabled .el-button--primary,
.disabled .el-button--danger {
  background-color: #dbdada;
  border: 1px solid #dbdada;
  color: #999;
  cursor: not-allowed;
}
.returnSubject {
  display: inline-block;
  padding-top:10px;
  margin-left: 216px;
  padding-bottom: 10px;
  font-size: 14px;
  color:#409eff;
}
</style>
